{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c3868eea",
   "metadata": {},
   "source": [
    "# 百度AI开放平台 \n",
    "## OCR（光学字符识别）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cce3ecb",
   "metadata": {},
   "source": [
    "###  通用文字识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d3d56b4",
   "metadata": {},
   "source": [
    "**接口描述**<en>    \n",
    ">在通用文字识别的基础上，提供更高精度的识别服务，支持更多语种识别（丹麦语、\n",
    "荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、\n",
    "泰语、越语、阿拉伯语、印地语及部分中国少数民族语言），并将字库从1w+扩展到2w+，\n",
    "能识别所有常用字和大部分生僻字。\n",
    "\n",
    "**请求示例**   \n",
    ">HTTP 方法：POST\n",
    "请求URL：https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\n",
    "    \n",
    "***请求参数***\n",
    ">1.url参数—token  \n",
    ">2.图片参数—图片文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "415e4726",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "906ec69a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和 url/pdf_file 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码后进行urlencode，要求base64编码和urlencode...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和 image/pdf_file 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整url，url长度不超过1024字节，url对应的图片base64编码后大小不超过1...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>pdf_file</td>\n",
       "      <td>和 image/url 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>PDF文件，base64编码后进行urlencode，要求base64编码和urlencod...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>pdf_file_num</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>需要识别的PDF文件的对应页码，当 pdf_file 参数有效时，识别传入页码的对应页面内容...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>language_type</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>auto_detect CHN_ENGENGJAPKORFRESPAPORGERITARUS...</td>\n",
       "      <td>识别语言类型，默认为CHN_ENG可选值包括：- auto_detect：自动检测语言，并识...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>detect_direction</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/1...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>paragraph</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否输出段落信息</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>probability</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否返回识别结果中每一行的置信度</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                 参数                  是否必选      类型  \\\n",
       "0             image    和 url/pdf_file 三选一  string   \n",
       "1               url  和 image/pdf_file 三选一  string   \n",
       "2          pdf_file       和 image/url 三选一  string   \n",
       "3      pdf_file_num                     否  string   \n",
       "4     language_type                     否  string   \n",
       "5  detect_direction                     否  string   \n",
       "6         paragraph                     否  string   \n",
       "7       probability                     否  string   \n",
       "\n",
       "                                               可选值范围  \\\n",
       "0                                                  -   \n",
       "1                                                  -   \n",
       "2                                                  -   \n",
       "3                                                  -   \n",
       "4  auto_detect CHN_ENGENGJAPKORFRESPAPORGERITARUS...   \n",
       "5                                         true/false   \n",
       "6                                         true/false   \n",
       "7                                         true/false   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码后进行urlencode，要求base64编码和urlencode...  \n",
       "1  图片完整url，url长度不超过1024字节，url对应的图片base64编码后大小不超过1...  \n",
       "2  PDF文件，base64编码后进行urlencode，要求base64编码和urlencod...  \n",
       "3  需要识别的PDF文件的对应页码，当 pdf_file 参数有效时，识别传入页码的对应页面内容...  \n",
       "4  识别语言类型，默认为CHN_ENG可选值包括：- auto_detect：自动检测语言，并识...  \n",
       "5  是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/1...  \n",
       "6                                           是否输出段落信息  \n",
       "7                                   是否返回识别结果中每一行的置信度  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_html('https://ai.baidu.com/ai-doc/OCR/1k3h7y3db')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b21e6371",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.bdc609c210f5b2f063708bf4a6243d95.315360000.1965717980.282335-25954496', 'expires_in': 2592000, 'session_key': '9mzdD0X76Rfk6mvOxxyKCY38VXlm0qCOCVL2LHNA55Je0hk0w4sCXvYIsLU2XhhFLBW9ufssPKMr92fiFltkGgrHlRgCng==', 'access_token': '24.4a8e840cb9f83d0dc9808f8b3b480cca.2592000.1652949980.282335-25954496', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '66f4dcef18a1c832a1cdc5070fc81e82'}\n"
     ]
    }
   ],
   "source": [
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "# 准备url参数(酬载)\n",
    "payload={\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'MIcKZXFcjgD6pZyMCdGBo2jf',\n",
    "    'client_secret':'8UoOD7t8aSnQHqVbGkANN4stfbGVky3F',\n",
    "    \n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())\n",
    "    access_token = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1d6f32de",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '世上没有'}, {'words': '绝望的处境'}, {'words': '只有对'}, {'words': '处境绝望的人'}, {'words': 'www.keaitupian.cn'}], 'words_result_num': 5, 'log_id': 1516337391998577411}\n"
     ]
    }
   ],
   "source": [
    "# 示例代码一\n",
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('rc.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a3bfd002",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '我所拥有的都是饶幸'}, {'words': '失去的都是人生'}], 'words_result_num': 2, 'log_id': 1516337396262102447}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('fq.webp', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "14754fd2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 48, 'left': 105, 'width': 254, 'height': 86}, 'words': '用舍由時'}, {'location': {'top': 123, 'left': 93, 'width': 275, 'height': 97}, 'words': '行藏在我'}], 'words_result_num': 2, 'log_id': 1516337401221430334}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('OIP-C.jifi.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8b34cd27",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [{'text': ['ihsuiefhiuhaeh'], 'type': 'QR_CODE'}], 'codes_result_num': 1, 'log_id': 1516338208021561142}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('23.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3e05b6c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'log_id': 1516338210261310268, 'error_msg': 'missing required parameter(s)', 'error_code': 282003}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('sf.webp', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2385032f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'result': {'AmountInWords': [{'word': '捌万圆整'}], 'InvoiceNumConfirm': [{'word': '27852341'}], 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '79999.999907'}], 'NoteDrawer': [{'word': '福田自助13'}], 'SellerAddress': [{'word': '深圳市福田区沙头街道天安社区温河大厦9280号天安富尔美花国恰备购,,景丽镇景期21A15859980570'}], 'CommodityNum': [{'row': '1', 'word': '1'}], 'SellerRegisterNum': [{'word': '44030400DK01291'}], 'MachineCode': [], 'Remarks': [{'word': '/1/<27代开企业税号:92440300MA5GY3069Y代开企业名称深圳市福田区大家保险岗园大展仁零店'}], 'SellerBank': [{'word': '000000'}], 'CommodityTaxRate': [{'row': '1', 'word': '***'}], 'TotalTax': [{'word': '***'}], 'InvoiceCodeConfirm': [{'word': '044032100104'}], 'CheckCode': [{'word': '74228966763121369457'}], 'InvoiceCode': [{'word': '044032100104'}], 'InvoiceDate': [{'word': '2022年01月05日'}], 'PurchaserRegisterNum': [{'word': '91440300349947539L'}], 'InvoiceTypeOrg': [{'word': '深圳增值税普通发票'}], 'OnlinePay': [], 'Password': [{'word': '966+7</4'}], 'Agent': [{'word': '是'}], 'AmountInFiguers': [{'word': '80000.00'}], 'PurchaserBank': [{'word': '中国农业银行41028900040054123'}], 'Checker': [{'word': '庞月晗'}], 'City': [{'word': '深圳'}], 'TotalAmount': [{'word': '80000.00'}], 'CommodityAmount': [{'row': '1', 'word': '80000.00'}], 'PurchaserName': [{'word': '大家人寿保险股份有限公司深圳分公司'}], 'CommodityType': [], 'Province': [{'word': '广东'}], 'InvoiceType': [{'word': '普通发票'}], 'SheetNum': [{'word': '第二联：发票联'}], 'PurchaserAddress': [{'word': '深圳市福田区华富街道彩园路东方新天地广场A座2304、2305、2206复式上管想分0755-36996395'}], 'CommodityTax': [{'row': '1', 'word': '***'}], 'CommodityPlateNum': [], 'CommodityUnit': [], 'Payee': [{'word': '庞月略'}], 'CommodityName': [{'row': '1', 'word': '代理手续费'}], 'SellerName': [{'word': '国家税务总局深圳市福田区税务局代开一百二十七代开'}], 'InvoiceNum': [{'word': '27852341'}]}, 'top': 13, 'left': 14, 'probability': 0.9994304776, 'width': 1245, 'type': 'vat_invoice', 'height': 735}], 'words_result_num': 1, 'x-aipe-self-def': 'aip:961=1', 'log_id': 1516338212436118506}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/multiple_invoice\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('fp.webp', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\"image\":img,\n",
    "'access_token':access_token\n",
    "        }\n",
    "         \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba66c044",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
